package losrebellos.lospistoleros.components.application.movieclip.swfaddress 
{
	import asual.swfaddress.SWFAddress;
	import asual.swfaddress.SWFAddressEvent;

	import losrebellos.console.Console;
	import losrebellos.lospistoleros.components.application.IPSwfAddressApplicationModel;
	import losrebellos.lospistoleros.components.application.movieclip.base.BasePApplicationControllerMovieClip;
	import losrebellos.lospistoleros.core.model.movieclip.IPModelMovieClip;
	import losrebellos.lospistoleros.core.view.movieclip.IPViewMovieClip;
	import losrebellos.lospistoleros.events.PNavigateEvent;

	/*
	 *
	 * @author los rebellos - ben@benoitvinay.com
	 *
	 */
	public class PSwfAddressApplicationControllerMovieClip extends BasePApplicationControllerMovieClip 
	{
		/*
		 *
		 * CONSTRUCTOR
		 *
		 */
		public function PSwfAddressApplicationControllerMovieClip(m:IPModelMovieClip, v:IPViewMovieClip = null, name:String = null, type:String = null)
		{
			super(m, v, name, type);
		}
		protected function get _sapaModel():IPSwfAddressApplicationModel
		{
			return _model as IPSwfAddressApplicationModel;
		}

		
		/*
		 *
		 * INTERACTION
		 *
		 */
		override public function initialize():void
		{
			SWFAddress.addEventListener(SWFAddressEvent.CHANGE, swfAddressChangedHandler);
			
			_view.addEventListener(PNavigateEvent.CHANGE, deeplinkingChangeHandler);
			this.addEventListener(PNavigateEvent.CHANGED, deeplinkingChangedHandler);
			
			swfAddressChangedHandler();
		}
		override public function finalize():void
		{
			SWFAddress.removeEventListener(SWFAddressEvent.CHANGE, swfAddressChangedHandler);
			
			_view.removeEventListener(PNavigateEvent.CHANGE, deeplinkingChangeHandler);
			this.removeEventListener(PNavigateEvent.CHANGED, deeplinkingChangedHandler);
		}
		
		
		/*
		 * 
		 * URL
		 * 
		 */
		// separate SWFAddress to the PNavigateEvent
		// set to private to avoid it beeing overridden
		private function swfAddressChangedHandler(e:SWFAddressEvent = null):void
		{
			this.dispatchEvent(new PNavigateEvent(PNavigateEvent.CHANGED, SWFAddress.getValue()));
		}
		//
		protected function deeplinkingChangeHandler(e:PNavigateEvent):void
		{
			SWFAddress.setValue(e.url);
			
			Console.output(this, "url change to: " + e.url + " " + e.urlHashed);
		}
		protected function deeplinkingChangedHandler(e:PNavigateEvent):void
		{
			_sapaModel.url = e.url;
			_sapaModel.urlHashed = e.urlHashed;
			
			Console.output(this, "url changed to: " + _sapaModel.url + " " + _sapaModel.urlHashed);
		}
	}
}